#include "widget.h"
#include "ui_widget.h"
#include <QFile>
#include <QSslKey>
#include <QUrlQuery>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    client = new QNetworkAccessManager(this);

    QFile certfile(":/server.crt");
    QFile keyfile(":/server.key");
    certfile.open(QIODevice::ReadOnly);
    keyfile.open(QIODevice::ReadOnly);
    QSslCertificate cert(&certfile);
    QSslKey key(&keyfile, QSsl::Rsa);
    certfile.close();
    keyfile.close();

    sslconfig.setLocalCertificate(cert);
    sslconfig.setPrivateKey(key);
    sslconfig.setPeerVerifyMode(QSslSocket::VerifyNone);

    QUrlQuery params;
    params.addQueryItem("appId", "gvd1ZIkWtGF7O3f5d3XbDXhTsVUa");
    params.addQueryItem("secret", "5nx4mWYRkswcCsQ0MjSlDfhq4QMa");

    QNetworkRequest request(QUrl("https://180.101.147.89:8743/iocm/app/sec/v1.1.0/login"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    request.setSslConfiguration(sslconfig);

    client->post(request, params.toString(QUrl::FullyEncoded).toUtf8());
    connect(client, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(onFinished(QNetworkReply*)));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::onFinished(QNetworkReply* reply)
{
    if (reply->error() != QNetworkReply::NoError)
    {
        qDebug() << reply->errorString();
    }
    else {
        QJsonDocument json = QJsonDocument::fromJson(reply->readAll());
        qDebug() << json.toJson();
        QJsonObject jsonobj = json.object();
        QString accessToken = jsonobj["accessToken"].toString();
        qDebug() << accessToken;
    }
    reply->deleteLater();
}
